package org.zn.note.jdk.beans;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

/**
 * @ClassName MyBean
 * @Author zn
 * @Date 2019/9/2 13:55
 **/
public class PropertyChangeSupportTest {

    private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        this.pcs.addPropertyChangeListener(listener);
    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        this.pcs.removePropertyChangeListener(listener);
    }

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        String oldValue = this.name;
        String newValue = name;
        this.pcs.firePropertyChange("name", oldValue, newValue);
        this.name = name;
    }

    public static void main(String[] args) {
        PropertyChangeSupportTest myBean = new PropertyChangeSupportTest();
        myBean.setName("Johnny");
        myBean.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                StringBuilder buffer = new StringBuilder();
                buffer.append("第一个PropertyChangeListener，");
                buffer.append("OldValue:").append(evt.getOldValue()).append(", ");
                buffer.append("NewValue:").append(evt.getNewValue()).append(", ");
                buffer.append("PropagationId:").append(evt.getPropagationId()).append(", ");
                buffer.append("PropertyName:").append(evt.getPropertyName()).append(", ");
                System.out.println(buffer);
            }
        });
        myBean.setName("Jack");
        myBean.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                StringBuilder buffer = new StringBuilder();
                buffer.append("第二个PropertyChangeListener。");
                System.out.println(buffer);
            }
        });
        myBean.setName("Jordan");
    }
}
